package com.example.zendesk_plugin

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import androidx.annotation.NonNull

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import zendesk.android.Zendesk
import zendesk.logger.Logger
import zendesk.messaging.android.DefaultMessagingFactory

/** ZendeskPlugin */
class ZendeskPlugin: FlutterPlugin, MethodCallHandler, ActivityAware {

  private lateinit var channel: MethodChannel
  private var context: Context? = null // 存储 Application Context
  private var activity: Activity? = null // 存储当前 Activity（可能为 null）

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "zendesk_plugin")
    channel.setMethodCallHandler(this)
    context = flutterPluginBinding.applicationContext // 获取 Application Context
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    if (call.method == "initZendeskSDK") {
      context?.let {  initZendeskSDK(call.arguments as String, it, callback = { isSuccess ->
        println("初始化SDK：$isSuccess")
        result.success(isSuccess)
      }) }
    } else if (call.method == "pushToConversation") {
      pushToConversation()
      result.success(true)
    } else if (call.method == "getUnreadCount") {
      getUnreadMessageCount()
      result.success(0)
    } else if (call.method == "setLoggerEnabled") {
      setLoggerEnabled(call.arguments as Boolean)
      result.success(true)
    } else if (call.method == "setLoggerLevel") {
      setLoggerLevel()
      result.success(true)
    } else {
      result.notImplemented()
    }
  }

  // 初始化SDK
  private fun initZendeskSDK(key: String, context: android.content.Context, callback: (Boolean) -> Unit) {
    Zendesk.initialize(
      context = context,
      channelKey = key,
      successCallback = { zendesk ->
        println("Initialization successful")
        callback(true)
      },
      failureCallback = { error ->
        // Tracking the cause of exceptions in your crash reporting dashboard will help to triage any unexpected failures in production
        println("Initialization failed: ${error.message}")
        callback(false)
      },
      messagingFactory = DefaultMessagingFactory()
    )
  }

  // 进入会话
  private fun pushToConversation() {
    activity?.let {  Zendesk.instance.messaging.showMessaging(it) }
  }

  // 获取未读消息数量
  private fun getUnreadMessageCount(): Int {
    return Zendesk.instance.messaging.getUnreadMessageCount()
  }

  // 开启日志
  private fun setLoggerEnabled(bool: Boolean) {
    Logger.setLoggable(bool)
  }

  // 设置日志级别
  private fun setLoggerLevel() {
    println("Android暂不支持该功能")
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    activity = binding.activity
  }

  override fun onDetachedFromActivityForConfigChanges() {
    activity = null
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    activity = binding.activity
  }

  override fun onDetachedFromActivity() {
    activity = null
  }
}




